import { IHooksOptions } from '@/hooks/interface'
import service from '@/utils/request'
import { onMounted } from 'vue'
import { clearEmptyProp } from '@/utils/tool'
import { Storage } from '@/utils/storage'
import { ElMessage, ElMessageBox } from 'element-plus'

export const useCrud = (options: IHooksOptions, t) => {
	let limitLocal = Storage.getItem('limitLocal') ? Number(Storage.getItem('limitLocal')) : 50
	if(isNaN(limitLocal)){
		limitLocal = 50
	}
	const defaultOptions: IHooksOptions = {
		diyDataProp:'',
		setSize:0,
		createdIsNeed: true,
		dataListUrl: '',
		isPage: true,
		deleteUrl: '',
		primaryKey: 'id',
		exportUrl: '',
		queryForm: {},
		dataList: [],
		order: '',
		asc: false,
		page: 1,
		per_page: limitLocal,
		total: 0,
		pageSizes: [5, 10, 15, 20, 25, 30, 40, 50, 100, 150, 200, 300, 500],
		dataListLoading: false,
		dataListSelections: []
	}

	const mergeDefaultOptions = (options: any, props: any): IHooksOptions => {
		for (const key in options) {
			if (!Object.getOwnPropertyDescriptor(props, key)) {
				props[key] = options[key]
			}
		}
		return props
	}

	// 覆盖默认值
	const state = mergeDefaultOptions(defaultOptions, options)

	onMounted(() => {
		if (state.createdIsNeed) {
			query()
		}
	})

	const query = () => {
		if (!state.dataListUrl) {
			return
		}

		state.dataListLoading = true
		console.log(state.queryForm);
		let params = {
			page: state.isPage ? state.page : null,
			per_page: state.isPage ? state.per_page : null,
			...clearEmptyProp(state.queryForm)
		}
		if(state.setSize){
			params.per_page = state.setSize
		}
		service
			.post(state.dataListUrl, params)
			.then((res: any) => {
				// // .console.log(res,'service');
				if(state.diyDataProp){
					state.dataList = res.data[state.diyDataProp].data
					state.total = res.data[state.diyDataProp].total
					state.allData = res.data[state.diyDataProp]
				}else{
					state.dataList = state.isPage && res.data.data ? res.data.data : res.data
					state.total = state.isPage && res.data.data ? res.data.total : res.data.length
					state.allData = res.data
				}
			}).finally(() => {
				state.dataListLoading = false
			})
	}

	const getDataList = () => {
		state.page = 1
		query()
	}

	const sizeChangeHandle = (val: number) => {
		Storage.setItem('limitLocal', val)
		state.page = 1
		state.per_page = val
		query()
	}

	const currentChangeHandle = (val: number) => {
		state.page = val
		query()
	}

	// 多选
	const selectionChangeHandle = (selections: any[]) => {
		state.dataListSelections = selections.map((item: any) => state.primaryKey && item[state.primaryKey])
	}

	// 排序
	const sortChangeHandle = (data: any) => {
		const { prop, order } = data

		if (prop && order) {
			state.order = prop
			state.asc = order === 'ascending'
		} else {
			state.order = ''
		}

		query()
	}

	const deleteHandle = (data: any,diyid: any = '') => {
		if (!state.deleteUrl) {
			return
		}

		ElMessageBox.confirm(t('axios.DeleteTips'), t('prompt'), {
			confirmButtonText: t('confirm'),
			cancelButtonText: t('cancel'),
			type: 'warning'
		})
			.then(() => {
				let url: any = state.deleteUrl
				let ajaxData: any = {}
				if(diyid){
					ajaxData[diyid] = data
				}else{
					ajaxData.id = data
				}
				service.post(url, ajaxData).then(() => {
					ElMessage.success(t('opaSuccess'))
					query()
				})
			})
			.catch(() => {})
	}

	const deleteBatchHandle = (key?: number | string) => {
		let data: any[] = []
		if (key) {
			data = [key]
		} else {
			data = state.dataListSelections ? state.dataListSelections : []

			if (data.length === 0) {
				ElMessage.warning(t('PleaseSelect'))
				return
			}
		}

		ElMessageBox.confirm(t('axios.DeleteTips'), t('prompt'), {
			confirmButtonText: t('confirm'),
			cancelButtonText: t('cancel'),
			type: 'warning'
		})
			.then(() => {
				if (state.deleteUrl) {
					service.delete(state.deleteUrl, { data }).then(() => {
						ElMessage.success(t('opaSuccess'))

						query()
					})
				}
			})
			.catch(() => {})
	}
	// 重置搜索
	const resetSearch = () => {
		Object.keys(state.queryForm).forEach(key => (state.queryForm[key] = ''));
		getDataList()
	}

	return { getDataList, sizeChangeHandle, currentChangeHandle, selectionChangeHandle, sortChangeHandle, deleteHandle, deleteBatchHandle, resetSearch }
}
